package com.zmj.solr.util;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class PropertiesUtils {

    private static final PropertiesUtils propertiesFiles = new PropertiesUtils();

    /**
     * 存放所有的属性配置文件对象
     */
    private Map<String, Properties> propertiesMap = new HashMap<String, Properties>();

    private PropertiesUtils() {
    }

    /**
     * 获得属性配置文件工具类的实例对象
     *
     * @return PropertiesUtils 对象
     */
    public static PropertiesUtils getInstance() {
        return propertiesFiles;
    }

    /**
     * 获取Properties文件对象
     *
     * @param propertiesFileName
     * @return
     * @throws IOException
     */
    public synchronized Properties getProperties(String propertiesFileName) throws IOException {
        if (propertiesFileName == null || "".equals(propertiesFileName)) {
            throw new IllegalArgumentException("The propertiesFileName is illegal argument!");
        }
        Properties prop = propertiesMap.get(propertiesFileName);
        if (prop == null) {
            prop = new Properties();
            //注意这个文件的InputStream，这里要修改
            InputStream is = this.getClass().getResourceAsStream(propertiesFileName);
            if (is == null) {
                throw new FileNotFoundException("The file \"" + propertiesFileName + "\" is  not found!");
            }
            prop.load(is);
            propertiesMap.put(propertiesFileName, prop);
        }
        return prop;
    }

    /**
     * 根据属性配置文件名称和属性名称获取属性配置值
     *
     * @param propertiesFileName
     *            属性配置文件名称
     * @param propertyName
     *            属性名称
     * @return 属性值
     * @throws IOException
     */
    public String getProperty(String propertiesFileName, String propertyName) throws IOException {
        Properties prop = getProperties(propertiesFileName);
        return prop.getProperty(propertyName);
    }

    /**
     * 获得Properties对象列表
     *
     * @return
     */
    public List<Properties> getProperties() {
        if (propertiesMap.isEmpty()) {
            return null;
        }

        return new LinkedList<Properties>(propertiesMap.values());
    }

    /**
     * 获得属性对象Map
     *
     * @return
     */
    public Map<String, Properties> getPropertiesMap() {
        return propertiesMap;
    }
}
